import time
from datetime import datetime

import requests

# 网易云音乐热搜榜API URL
url = 'https://music.163.com/api/cloudsearch/pc'

# 请求头，模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

# 搜索关键词参数
params = {
    's': '',
    'type': 1,  # 类型：1 单曲, 10 专辑, 100 歌手, 1000 歌单, 1002 用户, 1004 MV, 1006 歌词, 1009 电台, 1014 视频
    'offset': 0,
    'limit': 10  # 返回结果数量
}


def fetch_hot_songs():
    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        songs = data['result']['songs']
        print(f"获取时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        for song in songs:
            print(f"歌曲ID: {song['id']}, 歌曲名: {song['name']}, 歌手: {song['ar'][0]['name']}")
    except requests.RequestException as e:
        print(f"请求错误: {e}")
    except (KeyError, IndexError) as e:
        print(f"数据解析错误: {e}")


def main():
    while True:
        fetch_hot_songs()
        time.sleep(3600)  # 每小时执行一次


if __name__ == '__main__':
    main()
